package pers.liyan.shi.springclouddistributedlocker.configuration;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pers.liyan.shi.springclouddistributedlocker.zookeeper.ZooKeeperProperties;

/**
 * Curator 自动配置类
 * 主要用于注入分布式锁
 * @author ShiLY
 * @version 1.0
 * @date 2020/2/23 13:41
 */
@Configuration
@ConditionalOnClass(InterProcessMutex.class)
@EnableConfigurationProperties(ZooKeeperProperties.class)
public class CuratorAutoConfiguration {

    private final ZooKeeperProperties zooKeeperProperties;

    public CuratorAutoConfiguration(ZooKeeperProperties zooKeeperProperties) {
        this.zooKeeperProperties = zooKeeperProperties;
    }

    @Bean
    public InterProcessMutex interProcessMutex(){

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zooKeeperProperties.getConnectString())
                .sessionTimeoutMs(zooKeeperProperties.getSessionTimeoutMs())
                .connectionTimeoutMs(zooKeeperProperties.getConnectionTimeoutMs())
                .retryPolicy(retryPolicy)
                .build();
        client.start();
        return new InterProcessMutex(client, "/curator/lock");

    }

}
